package com.uenpay.im.ui.old.activity.videochat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.qyx.android.database.DBTalkMsgColumns;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.MsgType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.SessionModel;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.manage.ChatMsgManage;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.chatbean.MsgRefuseVideoChatModel;
import com.uenpay.im.weight.RoundImageView;
import com.qyx.videochat.util.VideoChatResultType;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author SL
 * @created 2016-2-17 下午5:41:25
 * @copyRight http://www.qiyunxin.com
 * @function 视频响应页面
 */
public class VideoChatResponseActivity extends BaseActivity {

    private RoundImageView call_avatar_iv;
    private TextView call_name_tv;
    private ImageView refuse_iv, answer_iv;
    private QyxMsg mQyxMsg = null;
    private MediaPlayer BackgroundMediaPlayer;
    private ChatMsgManage messageListHelper = null;
    private TalkMsgManager mTalkMsgManager = new TalkMsgManager();
    private CancelCallBroadcastReceiver mCancelCallBroadcastReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_video_chat_response_layout;
    }

    @Override
    public void initView(View view) {
        Bundle bundle = getIntent().getExtras();
        mQyxMsg = bundle.getParcelable("message");

        initView();
        initListener();
        initData();
        playSound("phonering.mp3", true);
    }

    protected void initView() {
        messageListHelper = new ChatMsgManage(this);
        call_avatar_iv = (RoundImageView) findViewById(R.id.call_avatar_iv);
        call_name_tv = (TextView) findViewById(R.id.call_name_tv);
        refuse_iv = (ImageView) findViewById(R.id.refuse_iv);
        answer_iv = (ImageView) findViewById(R.id.answer_iv);
    }

    protected void initListener() {
        refuse_iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                refuseVideoChat();
            }
        });
        answer_iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                answerVideoChat();
                finish();
            }
        });
    }

    private void initData() {
        if (mQyxMsg != null) {
            call_avatar_iv.SetUrl(APIConfiguration.getAvatarUrlNormal(
                    mQyxMsg.from_cust_id + "", PacketType.PERSONAL));
            call_name_tv.setText(mQyxMsg.from_cust_name);
        }
    }

    /**
     * 拒绝
     */
    private void refuseVideoChat() {
        if (mQyxMsg != null) {
            QyxMsg qyxMsg = new QyxMsg();
            qyxMsg.from_cust_id = mQyxMsg.to_cust_id;
            qyxMsg.from_cust_name = IMApplication.config.getUserName();
            qyxMsg.to_cust_id = mQyxMsg.from_cust_id;
            // qyxMsg.chat_type = PacketType.PERSONAL;
            qyxMsg.msg_content_type = MsgContentType.REFUSE_VIDEO_CHAT;
            qyxMsg.msg_type = MsgType.MSG_SENDS + "";
            qyxMsg.send_status = "";
            qyxMsg.content = mQyxMsg.msg_no;
            qyxMsg.msg_no = qyxMsg.getMsgNo(qyxMsg.from_cust_id + "",
                    qyxMsg.to_cust_id + "", qyxMsg.sessionModel.getSessionId()
                            + "");
            /** 将拒绝消息发送给视频通话请求方 **/
            MsgRefuseVideoChatModel chatModel = new MsgRefuseVideoChatModel();
            chatModel.setRefuseVideoChatMsgNo(mQyxMsg.msg_no);
            SessionModel sessionModel = new SessionModel();
            sessionModel.setSessionId(mQyxMsg.from_cust_id);
            sessionModel.setSessionType(PacketType.PERSONAL);
            chatModel.setToCustName(mQyxMsg.from_cust_name);
            chatModel.setFromCustName(IMApplication.getCustName());
            IMApplication.getInstance().sendMessage(chatModel,
                    sessionModel, null);
            /** 修改数据库视频通话结果 **/
            if (!TextUtils.isEmpty(mQyxMsg.content_json)) {
                try {
                    JSONObject json = new JSONObject(mQyxMsg.content_json);
                    if (json.has("video_chat_result")) {
                        json.remove("video_chat_result");
                    }
                    json.put("video_chat_result",
                            VideoChatResultType.VideoChatResultTypeRefuse);
                    mTalkMsgManager.updateFieldMsgByMsgNo(
                            DBTalkMsgColumns.CONTENT_JSON, json.toString(),
                            mQyxMsg.msg_no);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            /** 将拒绝消息发送给视频通话请求方 **/
            // TODO IMApplication.getInstance().sendMessage(qyxMsg,null);
            /** 修改视频通话消息结果 **/
            // mTalkMsgManager.updateFieldMsgByMsgNo(
            // DBTalkMsgColumns.VIDEO_CHAT_RESULT,
            // VideoChatResultType.VideoChatResultTypeRefuse + "",
            // mQyxMsg.msg_no);
            /** 刷新页面 **/
            Intent intent = new Intent(BroadcastAction.ACTION_REFUSE_VIDEO_CHAT);
            intent.putExtra("msg_no", mQyxMsg.msg_no);
            sendBroadcast(intent);
            /** 视频通话消息已读 **/
            mTalkMsgManager.updateFieldMsgByMsgNo(DBTalkMsgColumns.HAVE_READ,
                    "1", mQyxMsg.msg_no);

        }

        if (BackgroundMediaPlayer != null && BackgroundMediaPlayer.isPlaying()) {
            BackgroundMediaPlayer.pause();
        }
        finish();
    }

    /**
     * 接听
     */
    private void answerVideoChat() {
        if (mQyxMsg != null) {
            messageListHelper.connectToRoom1(mQyxMsg, false, 0);
        }
    }

    /**
     * 播放背景音乐
     *
     * @param path
     * @param isLoop
     */
    private void playSound(String name, boolean isLoop) {
        if (BackgroundMediaPlayer == null) {
            BackgroundMediaPlayer = new MediaPlayer();
        }
        if (BackgroundMediaPlayer != null) {
            BackgroundMediaPlayer.stop();
            BackgroundMediaPlayer.reset();
            BackgroundMediaPlayer.setLooping(isLoop);

            AssetManager am = getAssets();// ��ø�Ӧ�õ�AssetManager
            try {
                AssetFileDescriptor afd = am.openFd(name);
                BackgroundMediaPlayer.setDataSource(afd.getFileDescriptor(),
                        afd.getStartOffset(), afd.getLength());
                BackgroundMediaPlayer.prepare();
                BackgroundMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        if (mCancelCallBroadcastReceiver == null) {
            mCancelCallBroadcastReceiver = new CancelCallBroadcastReceiver();
            IntentFilter mIntentFilter = new IntentFilter(
                    BroadcastAction.ACTION_CANCEL_CALL_VIDEO_CHAT);
            registerReceiver(mCancelCallBroadcastReceiver, mIntentFilter);
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (BackgroundMediaPlayer != null) {
            BackgroundMediaPlayer.release();
            BackgroundMediaPlayer = null;
        }
        if (mCancelCallBroadcastReceiver != null) {
            unregisterReceiver(mCancelCallBroadcastReceiver);
        }
        super.onDestroy();
    }

    private class CancelCallBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equals(
                    BroadcastAction.ACTION_CANCEL_CALL_VIDEO_CHAT)) {
                // String msg_no = arg1.getStringExtra("msg_no");
                // mTalkMsgManager.updateFieldMsgByMsgNo(
                // DataBaseTalkMsgColumns.VIDEO_CHAT_RESULT,
                // VideoChatResultType.VideoChatResultTypeCancelCall + "",
                // msg_no);
                finish();
            }
        }

    }
}
